from ui.components.base.widget import TgBaseWidget
from .views.index_data_view import IndexDataView
from .controllers.index_data_controller import IndexDataController
from loguru import logger


class IndexDataTab(TgBaseWidget):
    """指数数据 Tab - MVC架构重构版本"""

    def __init__(self):
        super().__init__()
        self.view = IndexDataView()
        self.controller = IndexDataController()
        
        self._setup_mvc()
        self._initialize()

    def _setup_mvc(self):
        from ui.components.layouts.vbox_layout import TgVBoxLayout
        TgVBoxLayout(self).addWidget(self.view)
        self._connect_signals()

    def _connect_signals(self):
        self.view.query_button.clicked.connect(self._on_query_clicked)
        
        self.controller.data_loaded.connect(self.view.update_table_data)
        self.controller.ratio_data_loaded.connect(self.view.update_ratio_chart)
        self.controller.cumulative_return_loaded.connect(self.view.update_cumulative_return_chart)
        self.controller.volume_ratio_loaded.connect(self.view.update_volume_ratio_chart)
        self.controller.loading_state_changed.connect(self.view.set_query_loading)

    def _initialize(self):
        start_date, end_date = self.controller.get_default_date_range()
        self.view.set_default_dates(start_date, end_date)

    def _on_query_clicked(self):
        start_date, end_date = self.view.get_date_range()
        logger.info(f"开始查询大小比价数据，起始时间：{start_date}，结束时间：{end_date}")
        self.controller.load_chart_data(start_date, end_date)

    def cleanup(self):
        """清理资源"""
        self.controller.cleanup()
        self.view.clear_all_charts()

    def showEvent(self, event):
        # 当 Tab 可见时，启动定时刷新并立即刷新一次
        self.controller.start_auto_refresh()
        self.controller.load_table_data()
        super().showEvent(event)

    def hideEvent(self, event):
        # 当 Tab 隐藏时，停止定时刷新
        self.controller.stop_auto_refresh()
        super().hideEvent(event)